package com.example.sunmiv1.activity.member;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.activity.VipDetailsActivity;
import com.example.sunmiv1.adapter.MemberTimeAdapter;
import com.example.sunmiv1.adapter.MemberUserAdapter;
import com.example.sunmiv1.base.BaseActivity;
import com.example.sunmiv1.entity.LoginEntity;
import com.example.sunmiv1.entity.member.MemberAnalysisInfo;
import com.example.sunmiv1.entity.member.MemberGoodsClassInfo;
import com.example.sunmiv1.entity.member.MemberLabelManagerInfo;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.views.RecyclerViewNoScrollUtil;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.JustifyContent;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.content.ContentValues.TAG;

public class VipAnalysisActivity extends BaseActivity {


    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.vipAnalysis_search)
    ImageView vipAnalysisSearch;
    @BindView(R.id.vipAnalysis_edit)
    EditText vipAnalysisEdit;
    @BindView(R.id.vipAnalysis_screen)
    ImageView vipAnalysisScreen;
    @BindView(R.id.vipAnalysis_list)
    PullToRefreshListView vipAnalysisList;
    @BindView(R.id.memberAnalysis_time)
    RecyclerView memberAnalysisTime;
    @BindView(R.id.memberAnalysis_customTime)
    TextView memberAnalysisCustomTime;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.memberAnalysis_timeLin)
    LinearLayout memberAnalysisTimeLin;
    @BindView(R.id.memberAnalysis_num)
    RecyclerView memberAnalysisNum;
    @BindView(R.id.memberAnalysis_customNum)
    TextView memberAnalysisCustomNum;
    @BindView(R.id.memberAnalysis_numReduce)
    ImageView memberAnalysisNumReduce;
    @BindView(R.id.memberAnalysis_numEdit)
    EditText memberAnalysisNumEdit;
    @BindView(R.id.memberAnalysis_numAdd)
    ImageView memberAnalysisNumAdd;
    @BindView(R.id.memberAnalysis_numLin)
    LinearLayout memberAnalysisNumLin;
    @BindView(R.id.memberAnalysis_class)
    RecyclerView memberAnalysisClass;
    @BindView(R.id.memberAnalysis_classMore)
    TextView memberAnalysisClassMore;
    @BindView(R.id.memberAnalysis_money)
    RecyclerView memberAnalysisMoney;
    @BindView(R.id.memberAnalysis_customMoney)
    TextView memberAnalysisCustomMoney;
    @BindView(R.id.memberAnalysis_moneyStart)
    EditText memberAnalysisMoneyStart;
    @BindView(R.id.memberAnalysis_moneyEnd)
    EditText memberAnalysisMoneyEnd;
    @BindView(R.id.memberAnalysis_moneyConfirm)
    TextView memberAnalysisMoneyConfirm;
    @BindView(R.id.memberAnalysis_moneyLin)
    LinearLayout memberAnalysisMoneyLin;
    @BindView(R.id.memberAnalysis_label)
    RecyclerView memberAnalysisLabel;
    @BindView(R.id.memberAnalysis_labelMore)
    TextView memberAnalysisLabelMore;
    @BindView(R.id.vipAnalysis_screenReset)
    TextView vipAnalysisScreenReset;
    @BindView(R.id.vipAnalysis_screenConfirm)
    TextView vipAnalysisScreenConfirm;
    @BindView(R.id.vipAnalysis_screenLin)
    LinearLayout vipAnalysisScreenLin;
    @BindView(R.id.memberAnalysis_type)
    RecyclerView memberAnalysisType;

    private LoadingDialog loadingDialog;
    private Context context;

    private int page = 1;

    private MemberGoodsClassInfo memberGoodsClassInfo;
    private List<MemberGoodsClassInfo.DataBean.ListBean> goodsClassList = new ArrayList<>();
    private MemberTimeAdapter goodsClassAdapter;
    private String classId = "";

    private List<String> timeList = new ArrayList<>();//最近消費時間
    private MemberTimeAdapter timeAdapter;//最近消費時間適配器
    private String startTime = "", endTime = "";

    private List<String> numList = new ArrayList<>();//購買次數
    private MemberTimeAdapter numAdapter;//
    private String expense_num = "-1";//

    private List<String> moneyList = new ArrayList<>();//消費金額
    private MemberTimeAdapter moneyAdapter;//
    private String minMoney = "", maxMoney = "";

    private MemberAnalysisInfo memberAnalysisInfo;
    private List<MemberAnalysisInfo.DataBean.ListBean> analysisList = new ArrayList<>();
    private MemberUserAdapter memberUserAdapter;//會員分析列表適配器

    private MemberLabelManagerInfo memberLabelManagerInfo;
    private List<MemberLabelManagerInfo.DataBean.ListBean> labelList = new ArrayList<>();
    private MemberTimeAdapter labelAdapter;
    private String labelId = "";

    private List<String> memberType = new ArrayList<>();//會員類型
    private String type = "";
    private MemberTimeAdapter typeAdapter;

    private Intent intent;
    private ACache aCache;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    goodsClassList.add(new MemberGoodsClassInfo.DataBean.ListBean("0", "不限類目"));
                    goodsClassList.addAll(memberGoodsClassInfo.getData().getList());
                    setGoodsClassAdapter();

                    ViewGroup.LayoutParams params = memberAnalysisClass.getLayoutParams();
                    params.height = Tools.dp2px(50);
                    memberAnalysisClass.setLayoutParams(params);
                    break;
                case 2:
                    setGoodsClassAdapter();
                    break;
                case 3:
                    labelList.add(new MemberLabelManagerInfo.DataBean.ListBean("", "不限標籤", "", 0));
                    labelList.addAll(memberLabelManagerInfo.getData().getList());
                    setLabelAdapter();

                    ViewGroup.LayoutParams params1 = memberAnalysisLabel.getLayoutParams();
                    params1.height = Tools.dp2px(50);
                    memberAnalysisClass.setLayoutParams(params1);
                    break;
                case 4:
                    setLabelAdapter();
                    break;
                case 5:
                    analysisList.addAll(memberAnalysisInfo.getData().getList());
                    setMemberUserAdapter();
                    break;
                case 6:
                    setMemberUserAdapter();
                    break;
            }
        }
    };

    @Override
    protected void initView() {
        setContentView(R.layout.activity_vip_analysis);
        ButterKnife.bind(this);
        context = this;
        loadingDialog = new LoadingDialog(context);
        titleTitle.setText("會員分析");
    }

    @Override
    protected void initData() {
        aCache=ACache.get(this);
        memberType.add("不限類型");
        memberType.add("常規會員");
        memberType.add("PLUS會員");

        timeList.add("不限時間");
        timeList.add("一週內");
        timeList.add("兩週內");
        timeList.add("1個月內");
        timeList.add("2個月內");

        numList.add("不限次數");
        numList.add("0次");
        numList.add("1次");
        numList.add("2次");
        numList.add("3次");

        moneyList.add("不限金額");
        moneyList.add("0-500");
        moneyList.add("500-1000");
        moneyList.add("1000-2000");
        moneyList.add("2000+");
        memberAnalysisType.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        memberAnalysisTime.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        memberAnalysisNum.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        RecyclerViewNoScrollUtil recyclerViewNoScrollUtil = new RecyclerViewNoScrollUtil(context);
        recyclerViewNoScrollUtil.setScrollEnabled(false);
        recyclerViewNoScrollUtil.setFlexDirection(FlexDirection.ROW);
        recyclerViewNoScrollUtil.setFlexWrap(FlexWrap.WRAP);//按正常方向換行
        recyclerViewNoScrollUtil.setJustifyContent(JustifyContent.FLEX_START);//交叉軸的起點對齊。
        memberAnalysisClass.setLayoutManager(recyclerViewNoScrollUtil);
        memberAnalysisMoney.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        RecyclerViewNoScrollUtil recyclerViewNoScrollUtil1 = new RecyclerViewNoScrollUtil(context);
        recyclerViewNoScrollUtil1.setScrollEnabled(false);
        recyclerViewNoScrollUtil1.setFlexDirection(FlexDirection.ROW);
        recyclerViewNoScrollUtil1.setFlexWrap(FlexWrap.WRAP);//按正常方向換行
        recyclerViewNoScrollUtil1.setJustifyContent(JustifyContent.FLEX_START);//交叉軸的起點對齊。
        memberAnalysisLabel.setLayoutManager(recyclerViewNoScrollUtil1);
//        memberAnalysisTime.addItemDecoration(new SpacesItemDecoration(10, 10, false));
//        memberAnalysisNum.addItemDecoration(new SpacesItemDecoration(10, 10, false));
//        memberAnalysisClass.addItemDecoration(new SpacesItemDecoration(10, 10, false));
//        memberAnalysisMoney.addItemDecoration(new SpacesItemDecoration(10, 10, false));
//        memberAnalysisLabel.addItemDecoration(new SpacesItemDecoration(10, 10, false));
        setTypeAdapter();
        setTimeAdapter();
        setNumAdapter();
        setGoodsClassAdapter();
        setMoneyAdapter();
        setLabelAdapter();
        getGoodsClassSell();
        getUserLabel();
        getUserList();
    }

    /*private void setVipTypeAdapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select1, memberType);
        arrayAdapter.setDropDownViewResource(R.layout.item_drops);
        spinnerVipType.setAdapter(arrayAdapter);
    }*/
    private Calendar ca = Calendar.getInstance();
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    protected void initListener() {
        /*spinnerVipType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        type = "";
                        break;
                    case 1:
                        type = "3";
                        break;
                    case 2:
                        type = "2";
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });*/
        vipAnalysisList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                intent = new Intent(context, VipDetailsActivity.class);
                intent.putExtra("vid", analysisList.get(position - 1).getId());
                startActivity(intent);
            }
        });
        typeAdapter.Choose(index -> {
            typeAdapter.setIndex(index);
            switch (index) {
                case 0:
                    type = "";
                    break;
                case 1:
                    type = "3";
                    break;
                case 2:
                    type = "2";
                    break;
            }
//            page = 1;
//            analysisList.clear();
//            setMemberUserAdapter();
//            getUserList();
        });
        vipAnalysisList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                analysisList.clear();
                setMemberUserAdapter();
                getUserList();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getUserList();
            }
        });

        timeAdapter.Choose(index -> {
            timeAdapter.setIndex(index);
            switch (index) {
                case 0://不限
                    startTime = "";
                    endTime = "";
                    break;
                case 1://1周
                    endTime = Tools.stampToDateS(System.currentTimeMillis(), "yyyy-MM-dd") + " 23:59:59";
                    ca.setTime(new Date());
                    ca.add(Calendar.DATE, -7);
                    startTime = sdf.format(ca.getTime());
                    Log.e(TAG, "initListener: 開始時間是1==========" + sdf.format(ca.getTime()));
                    break;
                case 2://2周
                    endTime = Tools.stampToDateS(System.currentTimeMillis(), "yyyy-MM-dd") + " 23:59:59";
                    ca.setTime(new Date());
                    ca.add(Calendar.DATE, -14);
                    startTime = sdf.format(ca.getTime());
                    Log.e(TAG, "initListener: 開始時間是2==========" + sdf.format(ca.getTime()));
                    break;
                case 3://1個月
                    endTime = Tools.stampToDateS(System.currentTimeMillis(), "yyyy-MM-dd") + " 23:59:59";
                    ca.setTime(new Date());
                    ca.add(Calendar.MONTH, -1);
                    startTime = sdf.format(ca.getTime());
                    Log.e(TAG, "initListener: 開始時間是3==========" + sdf.format(ca.getTime()));
                    break;
                case 4://2個月
                    endTime = Tools.stampToDateS(System.currentTimeMillis(), "yyyy-MM-dd") + " 23:59:59";
                    ca.setTime(new Date());
                    ca.add(Calendar.MONTH, -2);
                    startTime = sdf.format(ca.getTime());
                    Log.e(TAG, "initListener: 開始時間是4==========" + sdf.format(ca.getTime()));
                    break;
            }
//            page = 1;
//            analysisList.clear();
//            setMemberUserAdapter();
//            getUserList();
        });
        numAdapter.Choose(index -> {
            numAdapter.setIndex(index);
            switch (index) {
                case 0:
                    expense_num = "-1";
                    break;
                case 1:
                    expense_num = "0";
                    break;
                case 2:
                    expense_num = "1";
                    break;
                case 3:
                    expense_num = "2";
                    break;
                case 4:
                    expense_num = "3";
                    break;
            }
//            page = 1;
//            analysisList.clear();
//            setMemberUserAdapter();
//            getUserList();
        });
        goodsClassAdapter.Choose(index -> {
            goodsClassAdapter.setIndex(index);
            classId = goodsClassList.get(index).getId();
//            page = 1;
//            analysisList.clear();
//            setMemberUserAdapter();
//            getUserList();
        });
        moneyAdapter.Choose(index -> {
            moneyAdapter.setIndex(index);
            switch (index) {
                case 0:
                    minMoney = "";
                    maxMoney = "";
                    break;
                case 1:
                    minMoney = "0";
                    maxMoney = "500";
                    break;
                case 2:
                    minMoney = "500";
                    maxMoney = "1000";
                    break;
                case 3:
                    minMoney = "1000";
                    maxMoney = "2000";
                    break;
                case 4:
                    minMoney = "2000";
                    maxMoney = "99999999";
                    break;
            }
//            page = 1;
//            analysisList.clear();
//            setMemberUserAdapter();
//            getUserList();
        });
        labelAdapter.Choose(index -> {
            labelAdapter.setIndex(index);
            labelId = labelList.get(index).getId();
//            page = 1;
//            analysisList.clear();
//            setMemberUserAdapter();
//            getUserList();
        });
        memberAnalysisNumEdit.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                if (TextUtils.isEmpty(memberAnalysisNumEdit.getText().toString().trim()) ||
                        Integer.parseInt(memberAnalysisNumEdit.getText().toString().trim()) == 0) {
                    memberAnalysisNumEdit.setText("1");
                }
                expense_num = memberAnalysisNumEdit.getText().toString().trim();
                page = 1;
                analysisList.clear();
                setMemberUserAdapter();
                getUserList();
            }
        });
    }

    /**
     * 最近消費時間適配器
     */
    private void setTypeAdapter() {
        if (typeAdapter == null) {
            typeAdapter = new MemberTimeAdapter(memberType);
            memberAnalysisType.setAdapter(typeAdapter);
        } else {
            typeAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 最近消費時間適配器
     */
    private void setTimeAdapter() {
        if (timeAdapter == null) {
            timeAdapter = new MemberTimeAdapter(timeList);
            memberAnalysisTime.setAdapter(timeAdapter);
        } else {
            timeAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 購買次數適配器
     */
    private void setNumAdapter() {
        if (numAdapter == null) {
            numAdapter = new MemberTimeAdapter(numList);
            memberAnalysisNum.setAdapter(numAdapter);
        } else {
            numAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 商品類目
     */
    private void setGoodsClassAdapter() {
        if (goodsClassAdapter == null) {
            goodsClassAdapter = new MemberTimeAdapter(goodsClassList);
            memberAnalysisClass.setAdapter(goodsClassAdapter);
        } else {
            goodsClassAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 商品類目
     */
    private void setLabelAdapter() {
        if (labelAdapter == null) {
            labelAdapter = new MemberTimeAdapter(labelList);
            memberAnalysisLabel.setAdapter(labelAdapter);
        } else {
            labelAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 消費金額適配器
     */
    private void setMoneyAdapter() {
        if (moneyAdapter == null) {
            moneyAdapter = new MemberTimeAdapter(moneyList);
            memberAnalysisMoney.setAdapter(moneyAdapter);
        } else {
            moneyAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 會員分析列表適配器
     */
    private void setMemberUserAdapter() {
        if (memberUserAdapter == null) {
            memberUserAdapter = new MemberUserAdapter(analysisList);
            vipAnalysisList.setAdapter(memberUserAdapter);
        } else {
            memberUserAdapter.notifyDataSetChanged();
        }
        /*memberUserAdapter.setClick(position -> {
            MemberBuyClassDialog.newInstance(analysisList.get(position).getId())
                    .startShow(getChildFragmentManager(), "")
                    .setCancelable(false);
        });*/
    }

    /**
     * 獲取商品類目
     */
    private void getGoodsClassSell() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("cashier_id",aCache.getAsString("uid"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        jsonObject = Tools.createParameterCode(jsonObject);
        HttpUtils.post(context, Common.GET_GOODS_CLASS_SELL, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                memberGoodsClassInfo = GsonUtils.JsonToBean(text, MemberGoodsClassInfo.class);
                Message msg = new Message();
                if (memberGoodsClassInfo.getStatus() == 1) {
                    msg.what = 1;
                } else {
                    msg.what = 2;
                }
                handler.sendMessage(msg);
            }

            @Override
            protected void onFailure(ResponseException e) {

            }
        });
    }

    /**
     * 獲取會員標籤
     */
    private void getUserLabel() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("cashier_id",aCache.getAsString("uid"));
            jsonObject.put("page", 1);
            jsonObject.put("pageSize", 100000);
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.GET_VIP_LABEL, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    memberLabelManagerInfo = GsonUtils.JsonToBean(text, MemberLabelManagerInfo.class);
                    Message msg = new Message();
                    if (memberLabelManagerInfo.getStatus() == 1) {
                        msg.what = 3;
                    } else {
                        msg.what = 4;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void reset() {
        memberAnalysisCustomTime.setText("自定義");
        memberAnalysisTimeLin.setVisibility(View.GONE);
        tvStartTime.setText("");
        tvEndTime.setText("");
        startTime = "";
        endTime = "";
        timeAdapter.setIndex(0);

        classId = "";
        goodsClassAdapter.setIndex(0);
        ViewGroup.LayoutParams params = memberAnalysisClass.getLayoutParams();
        params.height = Tools.dp2px(50);
        memberAnalysisClass.setLayoutParams(params);

        labelId = "";
        labelAdapter.setIndex(0);
        ViewGroup.LayoutParams params1 = memberAnalysisLabel.getLayoutParams();
        params1.height = Tools.dp2px(50);
        memberAnalysisLabel.setLayoutParams(params1);

        memberAnalysisCustomNum.setText("自定義");
        memberAnalysisNumLin.setVisibility(View.GONE);
        expense_num = "-1";
        numAdapter.setIndex(0);

        memberAnalysisCustomMoney.setText("自定義");
        memberAnalysisMoneyLin.setVisibility(View.GONE);
        minMoney = "0";
        maxMoney = "99999999";
        moneyAdapter.setIndex(0);
    }

    @OnClick({R.id.title_back, R.id.vipAnalysis_search, R.id.vipAnalysis_screen,
            R.id.memberAnalysis_customTime, R.id.memberAnalysis_classMore, R.id.memberAnalysis_labelMore,
            R.id.tv_start_time, R.id.tv_end_time,
            R.id.memberAnalysis_customNum, R.id.memberAnalysis_numReduce, R.id.memberAnalysis_numAdd,
            R.id.memberAnalysis_customMoney, R.id.memberAnalysis_moneyConfirm,
            R.id.vipAnalysis_screenReset, R.id.vipAnalysis_screenConfirm, R.id.vipAnalysis_screenLin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.vipAnalysis_screenLin:
                break;
            case R.id.vipAnalysis_screenReset:
                reset();
                break;
            case R.id.vipAnalysis_screenConfirm:
                vipAnalysisScreenLin.setVisibility(View.GONE);
                if (memberAnalysisTimeLin.getVisibility() == View.VISIBLE) {
                    if (TextUtils.isEmpty(startTime)) {
                        Toast.makeText(context, "請選擇消費開始時間", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (TextUtils.isEmpty(endTime)) {
                        Toast.makeText(context, "請選擇消費結束時間", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                if (TextUtils.isEmpty(minMoney)) {
                    Toast.makeText(context, "請輸入最低消費金額", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(maxMoney)) {
                    Toast.makeText(context, "請輸入最高消費金額", Toast.LENGTH_SHORT).show();
                    return;
                }

                page = 1;
                analysisList.clear();
                setMemberUserAdapter();
                getUserList();
                break;
            case R.id.title_back:
                finish();
                break;
            case R.id.vipAnalysis_screen:
                reset();
                vipAnalysisScreenLin.setVisibility(View.VISIBLE);
                break;

            case R.id.vipAnalysis_search:
                page = 1;
                analysisList.clear();
                setMemberUserAdapter();
                getUserList();
                break;
            case R.id.memberAnalysis_customTime:
                if (memberAnalysisTimeLin.getVisibility() == View.VISIBLE) {
                    memberAnalysisCustomTime.setText("自定義");
                    memberAnalysisTimeLin.setVisibility(View.GONE);
                    tvStartTime.setText("");
                    tvEndTime.setText("");
                    startTime = "";
                    endTime = "";
                    timeAdapter.setIndex(0);
//                    page = 1;
//                    analysisList.clear();
//                    setMemberUserAdapter();
//                    getUserList();
                } else {
                    memberAnalysisCustomTime.setText("已選擇時間");
                    timeAdapter.setIndex(9999);
                    memberAnalysisTimeLin.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.memberAnalysis_classMore:
                if ("更多".equals(memberAnalysisClassMore.getText().toString())) {
                    memberAnalysisClassMore.setText("收起");
                    setRecyclerViewHeight(memberAnalysisClass);
                } else {
                    memberAnalysisClassMore.setText("更多");
                    ViewGroup.LayoutParams params = memberAnalysisClass.getLayoutParams();
                    params.height = Tools.dp2px(50);
                    memberAnalysisClass.setLayoutParams(params);
                }
                break;
            case R.id.memberAnalysis_labelMore:
                if ("更多".equals(memberAnalysisLabelMore.getText().toString())) {
                    memberAnalysisLabelMore.setText("收起");
                    setRecyclerViewHeight(memberAnalysisLabel);
                } else {
                    memberAnalysisLabelMore.setText("更多");
                    ViewGroup.LayoutParams params = memberAnalysisLabel.getLayoutParams();
                    params.height = Tools.dp2px(50);
                    memberAnalysisLabel.setLayoutParams(params);
                }
                break;
            case R.id.tv_start_time:
                Tools.getDateFromDatePickerDialog(tvStartTime, time -> {
                    startTime = time;
                    if (!TextUtils.isEmpty(startTime) && !TextUtils.isEmpty(endTime)) {
//                        page = 1;
//                        analysisList.clear();
//                        setMemberUserAdapter();
//                        getUserList();
                    }
                });
                break;
            case R.id.tv_end_time:
                Tools.getDateFromDatePickerDialog(tvEndTime, time -> {
                    endTime = time;
                    if (!TextUtils.isEmpty(startTime) && !TextUtils.isEmpty(endTime)) {
//                        page = 1;
//                        analysisList.clear();
//                        setMemberUserAdapter();
//                        getUserList();
                    }
                });
                break;

            case R.id.memberAnalysis_customNum:
                if (memberAnalysisNumLin.getVisibility() == View.VISIBLE) {
                    memberAnalysisCustomNum.setText("自定義");
                    memberAnalysisNumLin.setVisibility(View.GONE);
                    expense_num = "-1";
                    numAdapter.setIndex(0);
//                    page = 1;
//                    analysisList.clear();
//                    setMemberUserAdapter();
//                    getUserList();
                } else {
                    memberAnalysisCustomNum.setText("已選擇次數");
                    numAdapter.setIndex(9999);
                    memberAnalysisNumEdit.setText("1");
                    memberAnalysisNumLin.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.memberAnalysis_numReduce:
                if (TextUtils.isEmpty(memberAnalysisNumEdit.getText().toString().trim()) ||
                        Integer.parseInt(memberAnalysisNumEdit.getText().toString().trim()) < 1) {
                    memberAnalysisNumEdit.setText("1");
                }
                if (Integer.parseInt(memberAnalysisNumEdit.getText().toString().trim()) <= 1) {
                    return;
                }
                memberAnalysisNumEdit.setText(String.valueOf(Integer.parseInt(memberAnalysisNumEdit.getText().toString().trim()) - 1));
                expense_num = memberAnalysisNumEdit.getText().toString().trim();
                break;
            case R.id.memberAnalysis_numAdd:
                memberAnalysisNumEdit.setText(String.valueOf(Integer.parseInt(memberAnalysisNumEdit.getText().toString().trim()) + 1));
                expense_num = memberAnalysisNumEdit.getText().toString().trim();
                break;
            case R.id.memberAnalysis_customMoney:
                if (memberAnalysisMoneyLin.getVisibility() == View.VISIBLE) {
                    memberAnalysisCustomMoney.setText("自定義");
                    memberAnalysisMoneyLin.setVisibility(View.GONE);
                    minMoney = "0";
                    maxMoney = "99999999";
                    moneyAdapter.setIndex(0);
//                    page = 1;
//                    analysisList.clear();
//                    setMemberUserAdapter();
//                    getUserList();
                } else {
                    memberAnalysisCustomMoney.setText("已選擇金額");
                    moneyAdapter.setIndex(9999);
                    minMoney = "";
                    maxMoney = "";
                    memberAnalysisMoneyStart.setText("");
                    memberAnalysisMoneyEnd.setText("");
                    memberAnalysisMoneyLin.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.memberAnalysis_moneyConfirm:
                if (TextUtils.isEmpty(memberAnalysisMoneyStart.getText().toString().trim())) {
                    Toast.makeText(context, "請輸入開始金額", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(memberAnalysisMoneyEnd.getText().toString().trim())) {
                    Toast.makeText(context, "請輸入結束金額", Toast.LENGTH_SHORT).show();
                    return;
                }
                minMoney = memberAnalysisMoneyStart.getText().toString().trim();
                maxMoney = memberAnalysisMoneyEnd.getText().toString().trim();
//                page = 1;
//                analysisList.clear();
//                setMemberUserAdapter();
//                getUserList();
                break;
        }
    }

    public void setRecyclerViewHeight(RecyclerView listView) {
        // 獲取 ListView 對應的 Adapter
        RecyclerView.Adapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        Log.e(TAG, "setRecyclerViewHeight: listAdapter.getItemCount()====" + listAdapter.getItemCount());
        int len = listAdapter.getItemCount() / 10;
        len = len + 1;
        if (len <= 0) {
            len = 1;
        }
        for (int i = 0; i < len; i++) {
            totalHeight += Tools.dp2px(35);
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;//totalHeight + (10 * (len - 1));
        Log.e(TAG, "setRecyclerViewHeight: params.height=====" + params.height);
        // listView.getDividerHeight () 獲取子項間分隔符佔用的高度
        // params.height 最後得到整個 ListView 完整顯示需要的高度
        listView.setLayoutParams(params);
    }

    /**
     * 獲取會員分析列表
     */
    private void getUserList() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("cashier_id",aCache.getAsString("uid"));
            jsonObject.put("search", vipAnalysisEdit.getText().toString().trim());
            jsonObject.put("member_type", type);
            jsonObject.put("start_time", startTime);//最近消費時間-起
            jsonObject.put("end_time", endTime);//最近消費時間-末
            jsonObject.put("expense_num", expense_num);//會員消費次數, 無限制時傳參 -1
            jsonObject.put("min_amount", minMoney);//消費金額-起
            jsonObject.put("max_amount", maxMoney);//消費金額-末
            jsonObject.put("vip_label", labelId);//會員標籤ID
            jsonObject.put("goods_class", classId);//商品類目ID
            jsonObject.put("page", page);
            jsonObject.put("pageSize", 20);
            jsonObject = Tools.createParameterCode(jsonObject);
            Log.d("測試18",jsonObject.toString());
            HttpUtils.post(context, Common.GET_USER_LIST, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    vipAnalysisList.onRefreshComplete();
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        if (json.getJSONObject("data") instanceof Object) {
                            memberAnalysisInfo = GsonUtils.JsonToBean(text, MemberAnalysisInfo.class);
                            Message msg = new Message();
                            if (memberAnalysisInfo.getStatus() == 1) {
                                page++;
                                msg.what = 5;
                            } else {
                                msg.what = 6;
                            }
                            handler.sendMessage(msg);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                    vipAnalysisList.onRefreshComplete();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
